﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Utils.Drawing;
using System.Diagnostics;

namespace Utils.Drawing
{
    public class AnimatedSprite : Sprite
    {
        AnimatedTexture animatedTexture;
        List<Animation> animations = new List<Animation>();
        Animation currentAnim;
        Animation defaultAnim;
        float frame = 0f;

        public AnimatedSprite(AnimatedTexture animatedTexture, Animation defaultAnim) : base(animatedTexture.Textures[0])
        {
            this.animatedTexture = animatedTexture;
            this.currentAnim = this.defaultAnim = defaultAnim;
            AddAnimation(defaultAnim);
        }

        public void AddAnimation(Animation animation)
        {
            Debug.Assert(animation.FirstFrame >= 0 && animation.LastFrame <= animatedTexture.Textures.Count,
                "Animation Frames out of bounds!");
            animations.Add(animation);
        }

        public void SetAnimation(Animation animation)
        {
            currentAnim = animation;
            frame = animation.FirstFrame;
        }

        public override void Draw(float dTime, SpriteRenderer renderer)
        {
            if(currentAnim != null)
            {
                if(!currentAnim.Update(ref frame, dTime))
                {
                    SetAnimation(defaultAnim);
                }
            }
            
            Debug.Assert(frame >=0 && frame < animatedTexture.Textures.Count, "Illegal Frame idx!");
            texture = animatedTexture.Textures[(int)frame];
            base.Draw(dTime, renderer);
        }
    }
}
